package com.atu.rtc;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.atu.rtc.bean.Candidate;
import com.atu.rtc.bean.Desc;
import com.atu.rtc.bean.Message;
import com.atu.rtc.factory.CameraCapturer;
import com.atu.rtc.factory.CapturerFactory;
import com.atu.rtc.factory.ICapturer;
import com.atu.rtc.factory.ScreenCapturer;
import com.atu.rtc.utils.Convert;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.webrtc.IceCandidate;
import org.webrtc.SessionDescription;
import org.webrtc.SurfaceViewRenderer;

import java.net.URI;
import java.net.URISyntaxException;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {
    private WebSocketClient client;

    private SurfaceViewRenderer localSurfaceView;
    private View cover;
    private ICapturer capturer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        localSurfaceView = findViewById(R.id.localSurfaceView);
        cover = findViewById(R.id.cover);
        CapturerFactory.register(1, new CameraCapturer(this, cover));
        CapturerFactory.register(2, new ScreenCapturer(this, cover, RECORD_REQUEST_CODE));
        initWebSocket();
    }

    private void send(String text) {
        if (client != null && client.isOpen()) {
            client.send(text);
        }
    }

    @AfterPermissionGranted(1)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
        if (EasyPermissions.hasPermissions(this, perms)) {
            Message message = new Message();
            message.setFromId(1001L);
            message.setType(1);
            send(Convert.toJson(message));
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "camera_and_location_rationale",
                    1, perms);
        }
    }

    private static final int RECORD_REQUEST_CODE = 101;
    private static final int STORAGE_REQUEST_CODE = 102;
    private static final int AUDIO_REQUEST_CODE = 103;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RECORD_REQUEST_CODE) {
            capturer.setIntent(data);
            capturer.connect();
        }

    }

    /**
     * 初始化WebSocket
     */
    private void initWebSocket() {
        try {

            client = new WebSocketClient(new URI("ws://192.168.0.199:8100/websocket")) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    System.out.println("连接成功");
                    methodRequiresTwoPermission();
                }

                @Override
                public void onMessage(String message) {
                    System.out.println(message);
                    Message msg = Convert.fromJson(message, Message.class);
                    switch (msg.getType()) {
                        case 2:
                            Desc desc = msg.getDesc();
                            SessionDescription sessionDescription = new SessionDescription(SessionDescription.Type.ANSWER, desc.getSdp());
                            capturer.setRemoteDescription(sessionDescription);
                            capturer.createAnswer();

                            break;
                        case 3:
                            Candidate candidate = msg.getCandidate();
                            IceCandidate iceCandidate = new IceCandidate(candidate.getSdpMid(), candidate.getSdpMLineIndex(), candidate.getCandidate());
                            capturer.addIceCandidate(iceCandidate);
                            break;
                        case 4:
                            capturer.createOffer();
                            break;
                        case 7:
                            capturer = CapturerFactory.getCapturer(msg.getCapturer());
                            capturer.init(client,localSurfaceView);
                            break;
                        case 8:
                            capturer.close();
                            break;
                    }
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    System.out.println("连接关闭");
                }

                @Override
                public void onError(Exception ex) {
                    System.out.println("连接失败" + ex.getMessage());
                }
            };

            client.connect();


        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}